﻿using AutoRevit.Entry.Command.Extends.HotUpdate;

namespace AutoRevit.Entry.Command;

/// <summary>
/// 具有自动执行扩展功能的命令基类
/// </summary>
public abstract class AutoCommand : IExternalCommand
{
    private static readonly IReadOnlyDictionary<Type, IExtendHandler> _extendHandler = new Dictionary<Type, IExtendHandler>()
    {
        { typeof(IHotUpdateExtend), new HotUpdateExtendHandler() },
        { typeof(IInterceptorExtend), new InterceptorExtendHandler() },
    };

    /// <summary>
    ///
    /// </summary>
    /// <param name="revitData"></param>
    /// <returns></returns>
    protected abstract Result Execute(IRevitData revitData);

    Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
        var data = RevitDataFactory.Create(commandData, elements);

        var interfaces = GetType().GetInterfaces();

        foreach (var extendHandler in from e in _extendHandler
                                      join i in interfaces on e.Key equals i
                                      select e)
        {
            var handlerResult = extendHandler.Value.Execute(data, this);

            message = data.ResultMessage!;

            if (!handlerResult.CanContinue)
            {
                return handlerResult.RevitResult;
            }
        }

        var result = Execute(data);

        message = data.ResultMessage!;

        return result;
    }
}